package lifecycle

import (
	"fmt"
	"sync"
	"time"
)

// LifecycleState 表示Actor的生命周期状态
type LifecycleState int

const (
	// LifecycleStateUninitialized 表示未初始化状态
	LifecycleStateUninitialized LifecycleState = iota
	// LifecycleStateInitialized 表示已初始化状态
	LifecycleStateInitialized
	// LifecycleStateRunning 表示运行中状态
	LifecycleStateRunning
	// LifecycleStatePaused 表示暂停状态
	LifecycleStatePaused
	// LifecycleStateStopped 表示已停止状态
	LifecycleStateStopped
	// LifecycleStateFailed 表示失败状态
	LifecycleStateFailed
)

// String 返回生命周期状态的字符串表示
func (s LifecycleState) String() string {
	switch s {
	case LifecycleStateUninitialized:
		return "uninitialized"
	case LifecycleStateInitialized:
		return "initialized"
	case LifecycleStateRunning:
		return "running"
	case LifecycleStatePaused:
		return "paused"
	case LifecycleStateStopped:
		return "stopped"
	case LifecycleStateFailed:
		return "failed"
	default:
		return "unknown"
	}
}

// ActorMetrics 包含Actor的指标信息
type ActorMetrics struct {
	// ID 是Actor的唯一标识符
	ID string
	// CreatedAt 是Actor的创建时间
	CreatedAt time.Time
	// LastActivityAt 是最后活动时间
	LastActivityAt time.Time
	// MessagesReceived 是接收到的消息数量
	MessagesReceived uint64
	// MessagesSent 是发送的消息数量
	MessagesSent uint64
	// ErrorCount 是错误数量
	ErrorCount uint64
	// LastError 是最后一个错误
	LastError error
	// LastErrorTime 是最后一个错误的时间
	LastErrorTime time.Time
}

// LifecycleAwareActor 是一个具有生命周期感知能力的Actor基类
type LifecycleAwareActor struct {
	// State 是Actor的当前状态
	State LifecycleState
	// Metrics 包含Actor的指标信息
	Metrics ActorMetrics
	// mu 是用于保护状态访问的互斥锁
	mu sync.RWMutex
}

// Initialize 初始化Actor
func (a *LifecycleAwareActor) Initialize(id string) {
	a.mu.Lock()
	defer a.mu.Unlock()

	a.State = LifecycleStateInitialized
	a.Metrics = ActorMetrics{
		ID:             id,
		CreatedAt:      time.Now(),
		LastActivityAt: time.Now(),
	}
}

// OnInit 初始化Actor，由子类重写
func (a *LifecycleAwareActor) OnInit() error {
	a.mu.Lock()
	defer a.mu.Unlock()

	if a.State != LifecycleStateInitialized {
		return fmt.Errorf("actor is not in initialized state, current state: %s", a.State)
	}

	return nil
}

// OnStart 启动Actor，由子类重写
func (a *LifecycleAwareActor) OnStart() error {
	a.mu.Lock()
	defer a.mu.Unlock()

	if a.State != LifecycleStateInitialized && a.State != LifecycleStateStopped && a.State != LifecycleStatePaused {
		return fmt.Errorf("actor cannot be started from state: %s", a.State)
	}

	a.State = LifecycleStateRunning
	a.Metrics.LastActivityAt = time.Now()
	return nil
}

// OnStop 停止Actor，由子类重写
func (a *LifecycleAwareActor) OnStop() error {
	a.mu.Lock()
	defer a.mu.Unlock()

	if a.State != LifecycleStateRunning && a.State != LifecycleStatePaused {
		return fmt.Errorf("actor cannot be stopped from state: %s", a.State)
	}

	a.State = LifecycleStateStopped
	a.Metrics.LastActivityAt = time.Now()
	return nil
}

// OnPause 暂停Actor，由子类重写
func (a *LifecycleAwareActor) OnPause() error {
	a.mu.Lock()
	defer a.mu.Unlock()

	if a.State != LifecycleStateRunning {
		return fmt.Errorf("actor cannot be paused from state: %s", a.State)
	}

	a.State = LifecycleStatePaused
	a.Metrics.LastActivityAt = time.Now()
	return nil
}

// OnResume 恢复Actor，由子类重写
func (a *LifecycleAwareActor) OnResume() error {
	a.mu.Lock()
	defer a.mu.Unlock()

	if a.State != LifecycleStatePaused {
		return fmt.Errorf("actor cannot be resumed from state: %s", a.State)
	}

	a.State = LifecycleStateRunning
	a.Metrics.LastActivityAt = time.Now()
	return nil
}

// IsRunning 检查Actor是否处于运行状态
func (a *LifecycleAwareActor) IsRunning() bool {
	a.mu.RLock()
	defer a.mu.RUnlock()
	return a.State == LifecycleStateRunning
}

// IsPaused 检查Actor是否处于暂停状态
func (a *LifecycleAwareActor) IsPaused() bool {
	a.mu.RLock()
	defer a.mu.RUnlock()
	return a.State == LifecycleStatePaused
}

// IsStopped 检查Actor是否处于停止状态
func (a *LifecycleAwareActor) IsStopped() bool {
	a.mu.RLock()
	defer a.mu.RUnlock()
	return a.State == LifecycleStateStopped
}

// RecordMessageReceived 记录接收到的消息
func (a *LifecycleAwareActor) RecordMessageReceived() {
	a.mu.Lock()
	defer a.mu.Unlock()
	a.Metrics.MessagesReceived++
	a.Metrics.LastActivityAt = time.Now()
}

// RecordMessageSent 记录发送的消息
func (a *LifecycleAwareActor) RecordMessageSent() {
	a.mu.Lock()
	defer a.mu.Unlock()
	a.Metrics.MessagesSent++
	a.Metrics.LastActivityAt = time.Now()
}

// RecordError 记录错误
func (a *LifecycleAwareActor) RecordError(err error) {
	a.mu.Lock()
	defer a.mu.Unlock()
	a.Metrics.ErrorCount++
	a.Metrics.LastError = err
	a.Metrics.LastErrorTime = time.Now()
	a.Metrics.LastActivityAt = time.Now()
}

// GetMetrics 获取Actor的指标信息
func (a *LifecycleAwareActor) GetMetrics() map[string]interface{} {
	a.mu.RLock()
	defer a.mu.RUnlock()

	metrics := map[string]interface{}{
		"id":                a.Metrics.ID,
		"state":             a.State.String(),
		"created_at":        a.Metrics.CreatedAt.Format(time.RFC3339),
		"last_activity_at":  a.Metrics.LastActivityAt.Format(time.RFC3339),
		"messages_received": a.Metrics.MessagesReceived,
		"messages_sent":     a.Metrics.MessagesSent,
		"error_count":       a.Metrics.ErrorCount,
	}

	if a.Metrics.LastError != nil {
		metrics["last_error"] = a.Metrics.LastError.Error()
		metrics["last_error_time"] = a.Metrics.LastErrorTime.Format(time.RFC3339)
	}

	return metrics
}

// String 返回Actor的字符串表示
func (a *LifecycleAwareActor) String() string {
	a.mu.RLock()
	defer a.mu.RUnlock()

	return fmt.Sprintf("Actor{id=%s, state=%s, messages_received=%d, messages_sent=%d, error_count=%d}",
		a.Metrics.ID,
		a.State.String(),
		a.Metrics.MessagesReceived,
		a.Metrics.MessagesSent,
		a.Metrics.ErrorCount)
}
